package service

import (
	"ai/internal/db/models"
	"ai/internal/repository"
	"errors"
	"time"

	"github.com/dgrijalva/jwt-go"
)

type UserService struct {
	userRepo *repository.UserRepository
}

func NewUserService(userRepo *repository.UserRepository) *UserService {
	return &UserService{userRepo: userRepo}
}

func (s *UserService) RegisterUser(username, password, role string) error {
	user := &models.User{
		Username: username,
		Password: password,
		Role:     role,
	}
	return s.userRepo.RegisterUser(user)
}

func (s *UserService) AuthenticateUser(username, password string) (*models.User, error) {
	user, err := s.userRepo.FindUserByUsername(username)
	if err != nil {
		return nil, err
	}
	// Add password verification logic here
	if user.Password != password {
		return nil, err
	}
	return user, nil
}

func (s *UserService) Authenticate(username, password string) (*models.User, error) {
	user, err := s.userRepo.FindUserByUsername(username)
	if err != nil || user.Password != password {
		return nil, errors.New("invalid username or password")
	}
	return user, nil
}

func (s *UserService) GenerateToken(user *models.User) (string, error) {
	// Define token claims
	claims := jwt.MapClaims{
		"username": user.Username,
		"exp":      time.Now().Add(time.Hour * 72).Unix(),
	}

	// Create token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte("your_secret_key"))
}
